const http = require('http')

/**
 * 获取有效的端口（如果传入端口无效，自动 +1 判断）
 * @param {*} port
 */

 async function getValidPort(port) {
  while (true) {
    let isValidPort = await checkPortValid(port);

    if (isValidPort) {
      break;
    }

    port++;
  }

  return port;
}


function checkPortValid(port) {
  return new Promise((resolve, reject) => {
    let server = http.createServer();

    server.on("listening", () => {
      server.close();
      resolve(true);
    });

    server.on("error", (error) => {
      if(error.code == 'EADDRINUSE'){
        resolve(false);
      } else {
        resolve(true);
      }
    });

    server.listen(port);
  });
}


module.exports = {
  getValidPort
}

